<template>
  <div id="app" v-loading.fullscreen.lock="requestLoading" :element-loading-text="loadingText"
    :element-loading-spinner="loadingIcon" :element-loading-background="ladingBgColor">
    <router-view />
    <PlayVoiceAudio ref="playVoiceAudio"></PlayVoiceAudio>
  </div>
</template>
<script>
import sha256 from "crypto-js/sha256";
import PlayVoiceAudio from "@/components/PlayVoiceAudio";
import EventBus from "./assets/js/eventBus";

export default {
  data() {
    return {
      asleepTimer: null,
      requestLoading: false,
      loadingText: "",
      loadingIcon: "",
      ladingBgColor: "rgba(255,255,255,.7)",
    };
  },
  methods: {
    closePageFun() {
      if (this.$store.getters.token) {
        this.$store.dispatch("SetTimeEnglish", 2);
      }
    },
    setStudyTime() {
      if (!localStorage.getItem("bookData")) {
        return;
      }
      let bookId = JSON.parse(localStorage.getItem("bookData")).book_id;
      let onlineTime = parseInt(
        (new Date().getTime() - this.$store.getters.startTime) / 1000
      );
      if (
        bookId &&
        this.$store.getters.startTime &&
        onlineTime &&
        onlineTime > 10 &&
        onlineTime < 2400
      ) {
        let params = {
          bookId,
          onlineTime,
        };
        params.key = parseInt(Math.random() * 10000, 10);
        params.timestamp = new Date().getTime();
        params.sign = sha256(
          `${params.key}:guoshi88-plus:${params.timestamp}`
        ).toString();
        let data = {
          bookId,
          onlineTime,
          token: this.$store.getters.token.substring(6).trim(),
        };
        let beaconStr = JSON.stringify(data);
        let url = `${this.baseAPI}englishStudentOnline/addEnglishStudentOnlineSendBeacon`;
        const queryStr = Object.keys(params)
          .reduce((ary, key) => {
            if (params[key]) {
              ary.push(
                encodeURIComponent(key) + "=" + encodeURIComponent(params[key])
              );
            }
            return ary;
          }, [])
          .join("&");
        url += `?${queryStr}`;
        let res = navigator.sendBeacon(url, beaconStr);
        console.log(res);
      }
    },
    setLevelTime() {
      let params = {};
      params.key = parseInt(Math.random() * 10000, 10);
      params.timestamp = new Date().getTime();
      params.sign = sha256(
        `${params.key}:guoshi88-plus:${params.timestamp}`
      ).toString();
      let data = {
        token: this.$store.getters.token.substring(6).trim(),
      };
      let beaconStr = JSON.stringify(data);
      let url = `${this.baseAPI}leave/updateLeaveTime`;
      const queryStr = Object.keys(params)
        .reduce((ary, key) => {
          if (params[key]) {
            ary.push(
              encodeURIComponent(key) + "=" + encodeURIComponent(params[key])
            );
          }
          return ary;
        }, [])
        .join("&");
      url += `?${queryStr}`;
      let res = navigator.sendBeacon(url, beaconStr);
      console.log(res);
    },
    beforeunloadFun() {
      if (this.$store.getters.token) {
        // 发送在线时长
        this.setStudyTime();
        // 发送离线请求
        // this.setLevelTime();
      }
    },
    domEvent() {
      this.asleepTimer.oldTime = new Date().getTime();
      if (!this.asleepTimer.timeoutObj) {
        console.log("重新开始", this.$store.getters.startTime);
        this.asleepTimer.start();
        if (this.$store.getters.token && !this.$store.getters.startTime) {
          this.$store.commit("SET_STARTTIME", 1);
        }
      }
    },
    // 十分钟不动提示
    setATimer() {
      let that = this;
      //十分钟不动
      this.asleepTimer = {
        timeout: 60000,
        timeoutObj: null,
        newTime: new Date().getTime(),
        oldTime: new Date().getTime(),
        outTime: 1800000,
        // outTime: 60000,
        reset: function () {
          if (this.timeoutObj) {
            clearTimeout(this.timeoutObj);
            this.timeoutObj = null;
          }
          return this;
        },
        start: function () {
          let self = this;
          self.timeoutObj = setTimeout(() => {
            self.newTime = new Date().getTime();
            if (self.newTime - self.oldTime > self.outTime) {
              //超时未操作
              that.closePageFun();
              self.reset();
              console.log("超时未操作", that.$store.getters.startTime);
            } else {
              if (
                that.$store.getters.startTime &&
                new Date().getTime() - that.$store.getters.startTime > 1800000
              ) {
                if (that.$store.getters.token) {
                  that.$store.dispatch("SetTimeEnglish", 1);
                }
              }
              self.reset().start();
              console.log("正常操作", that.$store.getters.startTime);
            }
          }, self.timeout);
        },
      };
    },
    watchVisibilitychange() {
      
      if (document.hidden) {
        this.$pauseAllAudio();
        this.$pauseAllVideo();
      } else {
        console.log("回来了");
      }
    },
    playVoice(type) {
      if (this.$refs.playVoiceAudio) {
        this.$refs.playVoiceAudio.changeType(type, true);
      }
    },
    //  禁掉buttonEnter
    keypress(e) {
      let kayCode = e.keyCode;
      let targetDom = e.target;
      if (kayCode == 13 && targetDom.tagName == "BUTTON") {
        e.preventDefault();
        return;
      }
    },
  },
  created() {
    localStorage.removeItem("classInfo");
    window.addEventListener("keypress", this.keypress);
    window.addEventListener("beforeunload", this.beforeunloadFun);
  },
  beforeDestroy() {
    this.closePageFun();
    document.body.removeEventListener("click", this.domEvent);
    document.body.removeEventListener("mousemove", this.domEvent);
    document.removeEventListener(
      "visibilitychange",
      this.watchVisibilitychange
    );
  },

  mounted() {
    if (this.$store.getters.token) {
      this.$store.commit("SET_STARTTIME", 1);
    }
    this.setATimer();
    this.asleepTimer.start();
    document.body.addEventListener("click", this.domEvent);
    document.body.addEventListener("mousemove", this.domEvent);
    // 监听页面是否可见，浏览器窗口切换回来时触发，可见时触发
    document.addEventListener("visibilitychange", this.watchVisibilitychange);
    EventBus.$on("playVoice", ({ type }) => {
      this.playVoice(type);
    });
    EventBus.$on("openLoading", ({ text, icon, bgColor }) => {
      this.loadingText = text ? text : "";
      this.loadingIcon = icon ? icon : "";
      this.ladingBgColor = bgColor ? bgColor : "";
      this.requestLoading = true;
    });
    EventBus.$on("closeLoading", () => {
      this.requestLoading = false;
    });
    // window.onbeforeunload = (e) => {
    //   e = e || window.event;
      // if (e) {
      //   e.returnValue = '关闭提示';
      // }

      //  this.toCloseFun()//调用自己的方法

      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
    //   return '关闭提示';
    // };
  },

  components: {
    PlayVoiceAudio,
  },
};
</script>
<style>
#app{
  font-size: 12px;
}
</style>
